package com.michale.admin.controller.monitor;

import com.github.pagehelper.PageInfo;
import com.michale.admin.controller.tool.BaseController;
import com.michale.common.annotation.Log;
import com.michale.common.constants.RedisCacheConstant;
import com.michale.common.domain.operate.UserOnlineEntity;
import com.michale.common.domain.security.LoginUserDetail;
import com.michale.common.enmus.BusinessType;
import com.michale.common.result.AjaxResult;
import com.michale.common.result.PageResult;
import com.michale.common.utils.redis.RedisUtils;
import com.michale.system.service.UserOnlineService;
import com.michale.system.service.UserService;
import io.swagger.annotations.Api;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Michale
 * @apiNote 在线用户管理
 */
@Api(tags = "在线用户管理")
@RestController
@RequestMapping("monitor/online")
public class OnlineController extends BaseController {

    @Resource
    private RedisUtils redisUtils;
    @Resource
    private UserService userService;
    @Resource
    private UserOnlineService userOnlineService;

    /**
     * 查询-在线用户
     *
     * @param ipAddress IP地址
     * @param userName  用户名
     * @return 在线用户列表
     */
    @GetMapping("/onlineList")
    @PreAuthorize("@security.isPermission('monitor:online:list')")
    public PageResult onlineList(String ipAddress, String userName) {
        startPage();
        List<UserOnlineEntity> userOnlineEntityList = userOnlineService.onlineList(ipAddress, userName);
        PageInfo<UserOnlineEntity> pageInfo = new PageInfo<>(userOnlineEntityList);
        return pageResult(pageInfo);
    }

    /**
     * 强制退出
     *
     * @param tokenId 会话ID
     * @return 结果
     */
    @DeleteMapping("/forceLogout/{tokenId}")
    @Log(title = "在线管理", businessType = BusinessType.FORCE)
    public AjaxResult forceLogout(@PathVariable String tokenId) {
        LoginUserDetail loginUserDetail = redisUtils.getCacheObject(RedisCacheConstant.LOGIN_TOKEN_KEY + tokenId);
        userService.checkUserAllowed(loginUserDetail.getUserEntity());
        userOnlineService.forceLogout(tokenId);
        return AjaxResult.success();
    }
}
